from django.shortcuts import render
from django.views import View
from django import http
import random, logging
from django_redis import get_redis_connection

from verifications.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE
from verifications.libs import constants  # 模板数字
from celery_tasks.sms.tasks import send_sms_code


logger = logging.getLogger("django")


# 图形验证码
class ImageCodeView(View):
    def get(self, request, uuid):
        # 获取图形验证码
        text, image = captcha.generate_captcha()
        # 存储图形验证码 文字存储到redis数据库
        coonect_redis = get_redis_connection('verify_code')
        coonect_redis.setex("img %s" % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 响应图形验证码
        return http.HttpResponse(image, content_type="image/jpg")


# 短信验证码
class SMSCodeView(View):
    def get(self, request, mobile):

        # 接收参数
        image_code_client = request.GET.get("image_code")
        uuid = request.GET.get("uuid")
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden("缺少必传参数")

        # 连接数据库
        redis_coon = get_redis_connection("verify_code")

        # 避免60秒发送短信 4002
        send_flag = redis_coon.get("send_flag %s" % mobile)
        if send_flag:
            return http.JsonResponse({"code": RETCODE.THROTTLINGERR, "errmsg": "短信验证码发送频繁"})

        # 提取数据库的验证码
        image_code_server = redis_coon.get("img %s" % uuid)
        # 判断图形验证码过期或者是否存在
        if image_code_server is None:
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码失效"})
        # 删除验证码
        redis_coon.delete("img %s" % uuid)
        # 转码
        image_code_server_str = image_code_server.decode("utf-8")
        if image_code_client.lower() != image_code_server_str.lower():   # 转换小写比较
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码输入错误"})

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        # log日志
        logger.info(sms_code)

        # 创建redis管道
        pl = redis_coon.pipeline()
        pl.setex("sms %s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag %s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()

        send_sms_code.delay(mobile, sms_code)
        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "发送短信验证码成功"})




